import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> datas = [
    "傻大黑粗",
    "有钱",
    "任性",
    "人傻钱多",
    "器大活好",
    "逗比",
  ];

  @override
  Widget build(BuildContext context) {
    var count = 0;
    var wrap = Wrap(
      children: datas.map((d) {
        var i = count;
        count++;
        return _buildItem(i);
      }).toList(),
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Container(
        child: wrap,
      ),
    );
  }

  var current = -1;
  bool startDrag = false;

  Widget _buildItem(int i) {
    Widget widget = Material(
      child: Chip(label: Text(datas[i].toString())),
      color: Colors.transparent,
    );

    return DragTarget<String>(
      builder: (context, srcDatas, __) {
        return Draggable<String>(
          feedback: Opacity(
            opacity: 1.0,
            child: widget,
          ),
          child: widget,
          childWhenDragging: Opacity(
            opacity: 0.5,
            child: widget,
          ),
          data: datas[i],
          onDragStarted: () {
            current = i;
            startDrag = true;
          },
          onDragCompleted: () {
            startDrag = false;
            current = -1;
          },
        );
      },
      onAccept: _onAccept,
      onLeave: onLeave,
      onWillAccept: (data) => onWillAccept(data, i),
    );
  }

  void move(int src, int target) {
    if (src == target) {
      return;
    }
    List<String> sub;

    String srcData = datas[src];
    if (src < target) {
      //0 to 2

      // 取 1，2序号 填充到 0 1位置
      sub = datas.sublist(src + 1, target + 1);
      datas.setRange(src, target, sub);
    } else {
      // 2 to 0

      // 取0 1 填充到 1，2
      sub = datas.sublist(target, src);
      datas.setRange(target + 1, src + 1, sub);
    }
    datas[target] = srcData;
    setState(() {});
  }

  void _onAccept(String data) {
    print("accept data = $data");
  }

  void onLeave(String data) {
    print("onLeave data = $data");
  }

  bool onWillAccept(String target, int srcIndex) {
    print("onWillAccept data = $target");
    var t = datas.indexOf(target);
    print("src = $t , target = $srcIndex");
    move(t, srcIndex);
    return true;
  }
}
